package org.jeecg.modules.business.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.mapper.CaishuiBusinessMapper;
import org.jeecg.modules.business.service.ICaishuiBusinessService;
import org.jeecg.modules.business.service.ICaishuiCompanySetService;
import org.jeecg.modules.business.vo.BusinessAccountVo;
import org.jeecg.modules.finance.mapper.CaishuiRechargeMapper;
import org.jeecg.modules.finance.mapper.CaishuiRefundRecordMapper;
import org.jeecg.modules.settle.mapper.CaishuiTaskSettleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 商户信息[B端]
 * @Author: yfkj
 * @Date: 2023-02-07
 * @Version: V1.0
 */
@Api(tags = "商户信息[B端]")
@RestController
@RequestMapping("/account/business")
@Slf4j
public class CaishuiBusinessController {

    @Autowired
    private ICaishuiBusinessService iCaishuiBusinessService;
    @Resource
    private CaishuiRechargeMapper caishuiRechargeMapper;
    @Resource
    private CaishuiTaskSettleMapper caishuiTaskSettleMapper;
    @Resource
    private CaishuiRefundRecordMapper caishuiRefundRecordMapper;
    @Resource
    private ICaishuiCompanySetService iCaishuiCompanySetService;


    /**
     * 查询当前登录商户账户信息
     *
     * @return
     */
    @ApiOperation(value = "商户信息[B端]-查询当前登录商户账户信息", notes = "商户信息[B端]-查询当前登录商户账户信息")
    @GetMapping(value = "/queryBusinessAccount")
    public Result<BusinessAccountVo> queryBusinessAccount() {
		BusinessAccountVo businessAccountVo = iCaishuiBusinessService.queryAccount(TokenUtils.getLoginUser().getCurBusiness(),
				TokenUtils.getLoginUser().getCurCompany());
		businessAccountVo.setBalance(0.00);
		if(oConvertUtils.isNotEmpty(businessAccountVo.getMainAccount())
				&& oConvertUtils.isNotEmpty(businessAccountVo.getSubAccountId())){
			//查询银行接口
            BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(businessAccountVo.getMainAccount());
            Result result = CMBApi.querySubUnitBalance(businessAccountVo.getMainAccount(),businessAccountVo.getSubAccountId(), bankSetDTO);
            if(result.isSuccess()){
                businessAccountVo.setBalance(oConvertUtils.getDouble(result.getResult().toString(),0.00));
            }
		}
        return Result.OK(businessAccountVo);
    }

    /**
     * 查询首页统计
     *
     * @return
     */
    @ApiOperation(value = "商户信息[B端]-查询首页统计", notes = "商户信息[B端]-查询首页统计")
    @GetMapping(value = "/queryIndexStatistics")
    public Result<?> queryIndexStatistics(@RequestParam(name="dateType",required=false) String dateType,
										  @RequestParam(name="timeBegin",required=false) String timeBegin,
										  @RequestParam(name="timeEnd",required=false) String timeEnd) {
		JSONObject result = new JSONObject(3);
		//当前登录用户
		LoginUser loginUser = TokenUtils.getLoginUser();
		//公共查询条件
		Map<String, String> params = new HashMap<>();
		params.put("businessId",loginUser.getCurBusiness());
        params.put("companyId",loginUser.getCurCompany());
		params.put("dateType",dateType);
		params.put("timeBegin",timeBegin);
		params.put("timeEnd",timeEnd);

		//查询充值金额、服务费
		Map<String, String> r_params = new HashMap<>();
		r_params.put("status","1");
		params.putAll(r_params);
		Map<String,Object> r_map = caishuiRechargeMapper.queryTotalAmount(params);
		result.put("rechargeAmount", oConvertUtils.getDouble(r_map.get("amount")+"",0.00));

		//查询下发金额、服务费
		Map<String, String> w_params = new HashMap<>();
		w_params.put("status","2");
		w_params.put("extendStatus","2");
		params.putAll(w_params);
		Map<String,Object> w_map = caishuiTaskSettleMapper.queryCaishuiTaskSettleTotal(params);
		result.put("withdrawalAmount", oConvertUtils.getDouble(w_map.get("successAmount")+"",0.00));
		result.put("serviceFee",oConvertUtils.getDouble(w_map.get("successServiceFee")+"",0.00));

		//查询退款金额、退款服务费
        Map<String, String> t_params = new HashMap<>();
        t_params.put("status","4");
        params.putAll(t_params);
        Map<String,Object> t_map = caishuiRefundRecordMapper.queryRefundTotal(params);
		result.put("drawbackAmount",oConvertUtils.getDouble(t_map.get("money")+"",0.00));
		result.put("drawbackServiceCharge",oConvertUtils.getDouble(t_map.get("serviceFee")+"",0.00));
		return Result.OK(result);
    }

	/**
	 * 查询首页最新充值记录
	 * @return
	 */
	@ApiOperation(value = "商户信息[B端]-查询首页最新充值记录", notes = "商户信息[B端]-查询首页最新充值记录")
	@GetMapping(value = "/queryIndexNewList")
	public Result<?> queryIndexNewList() {
		//当前登录用户
		LoginUser loginUser = TokenUtils.getLoginUser();
		//公共查询条件
		Map<String, String> params = new HashMap<>();
		params.put("businessId",loginUser.getCurBusiness());
        params.put("companyId",loginUser.getCurCompany());
		return Result.OK(caishuiRechargeMapper.queryNewList(params));
	}

    /**
     * 下载模板文件
     * @param response
     * @param fileName
     */
    @GetMapping("/templateDownload")
    public void templateDownload(HttpServletResponse response,
                                 @RequestParam(name="fileName",required=true) String fileName) {
        System.out.println("===fileName===:" + fileName);
        OutputStream out = null;
        try {
            // resources下路径，比如文件位置在：resources/file/test.docx
            String path = "/templates/" + fileName;
            InputStream inputStream = this.getClass().getResourceAsStream(path);
            System.out.println("===fileName===:" + inputStream);
            //强制下载不打开
            response.setContentType("application/force-download");
            out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            inputStream.close();
            out.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("下载失败！");
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



}
